package com.source.utils;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.IService;
import com.source.baseData.entity.SlaughterHouse;
import com.source.listener.ExcelListener;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Iceberg777
 * @since 2021-02-15
 */
public class ExcelUtil {

    /**
     * 下载excel
     * @param response  传入当前response
     * @param c Class文件，获取名字
     * @throws IOException  异常
     */
    public static void downloadExcel(HttpServletResponse response, Class c, List list) {

        //获取名字
        String cName = c.getName();
        int i = cName.lastIndexOf(".");
        String name = cName.substring(i + 1);

        String filename = null;
        try {
            filename = URLEncoder.encode(name,"utf-8").replaceAll("\\+","%20");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition","attachment;filename*=utf-8''" + filename + ".xlsx");
            EasyExcel.write(response.getOutputStream(), c).sheet("sheet1").doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传excel，存储数据到数据库中
     * @param excelFile excel文件
     * @param c class文件解析
     * @param iService  用于监听器
     * @throws IOException  异常
     */
    public static void uploadExcel(MultipartFile excelFile, Class c, IService iService) throws IOException {
        InputStream inputStream = excelFile.getInputStream();
        EasyExcel.read(inputStream, c, new ExcelListener(iService)).sheet().doRead();
        inputStream.close();
    }
}
